package org.example.cmsvue.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.spring.SpringUtil;
import lombok.AllArgsConstructor;
import org.example.cmsvue.entity.Departments;
import org.example.cmsvue.entity.Roles;
import org.example.cmsvue.entity.Users;
import org.example.cmsvue.service.IDepartmentsService;
import org.example.cmsvue.service.IRolesService;
import org.example.cmsvue.service.IUsersService;
import org.example.cmsvue.utils.R;
import org.example.cmsvue.vo.UserVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author laifeng
 * @since 2025-02-19
 */

@RestController
@RequestMapping("/users")
@AllArgsConstructor
public class UsersController {
    private final IUsersService usersServices;
    private final IDepartmentsService departmentService;
    private final IRolesService rolesService;

    @PostMapping("/login")
    public R doLogin(@RequestBody Users input) {
        Users user = usersServices.lambdaQuery().eq(Users::getName, input.getName()).one();
        if (user == null || !user.getPassword().equals(input.getPassword())) {
            return R.fail("用户名或密码错误");
        }
        StpUtil.login(user.getId());
        // 获取当前会话的 token 值
        String tokenValue = StpUtil.getTokenValue();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token", tokenValue);
        hashMap.put("id", user.getId());
        hashMap.put("name", user.getName());
        return R.success(hashMap);
    }

    @RequestMapping("/{id}")
    public R getUserInfo(@PathVariable("id") Integer id) {

        Users user = usersServices.getById(id);
        if (user==null){
            return R.fail("用户不存在");
        }
        Departments departments = departmentService.getById(user.getDepartmentId());
        Roles role = rolesService.getById(user.getRoleId());
        UserVo vo = new UserVo();
        BeanUtil.copyProperties(user, vo);
        vo.setRole(role);
        vo.setDepartment(departments);
        return R.success(vo);
    }

}
